package com.ztc.util.notify;

import com.ztc.common.alipay.Alipay;
import com.ztc.common.wechatpay.WeChatPay;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.ztc.ZtcOrder.bean.ZtcOrder;
import com.ztc.ZtcOrder.dao.ZtcOrderDao;
import com.ztc.ZtcOrder.service.ZtcOrderManager;
import com.ztc.util.enums.WalletLogType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 异步通知回调处理类
 */
@Controller
@RequestMapping("notify")
public class NotifyAction {
    public static void main(String[] args) {
        System.out.println(WalletLogType.getName(1));
    }

    @Autowired
    private ZtcOrderManager ztcOrderManager;
    @Autowired
    private ZtcOrderDao ztcOrderDao;

    private static final Logger LOGGER = LogManager.getLogger(WeChatPay.class);

//    /**
//     * 微信异步通知回调
//     * @param request 请求对象
//     * @param response 响应对象
//     * @throws IOException 可能会抛出IO流异常
//     */
//    @RequestMapping("/weChatNotify")
//    public void weChatNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        PrintWriter out = response.getWriter();
//        InputStream inStream = request.getInputStream();
//        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len = 0;
//        while ((len = inStream.read(buffer)) != -1) {
//            outSteam.write(buffer, 0, len);
//        }
//        outSteam.close();
//        inStream.close();
//        String result = new String(outSteam.toByteArray(), "utf-8");
//        XmlMapper xmlMapper = new XmlMapper();
//        Map<String, String> xmlMap = xmlMapper.readValue(result, Map.class);
//        // 此处调用订单查询接口验证是否交易成功
//        Boolean isTrue = WeChatPay.checkOrderQuery(xmlMap);
//        // 支付成功，商户处理后同步返回给微信参数
//        if (!isTrue) {
//            LOGGER.error("=========微信回调处理失败========="+result);
//            out.print("ERROR");
//        } else {
//            handleOrder(xmlMap,out);
//        }
//    }
//
//    /**
//     * 支付宝异步通知回调
//     * @param request 请求对象
//     * @param response 响应对象
//     * @throws IOException
//     */
//    @RequestMapping("/AliPayNotify")
//    public void AliPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        PrintWriter out = response.getWriter();
//        InputStream inStream = request.getInputStream();
//        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len = 0;
//        while ((len = inStream.read(buffer)) != -1) {
//            outSteam.write(buffer, 0, len);
//        }
//        outSteam.close();
//        inStream.close();
//        String result = new String(outSteam.toByteArray(), "utf-8");
//        ObjectMapper objectMapper = new ObjectMapper();
//        Map<String, String> xmlMap = objectMapper.readValue(result, Map.class);
//        // 此处调用订单查询接口验证是否交易成功
//        ZtcOrder ztcOrder = ztcOrderDao.findUniqueBy("orderNumber",xmlMap.get("out_trade_no"));
//        if(ztcOrder==null){
//            LOGGER.error("=========支付宝回调获取订单信息失败========="+result);
//            out.print("failure");
//        }
//        String outTradeNo = ztcOrder.getOrderNumber();
//        BigDecimal totalAmount = new BigDecimal(ztcOrder.getOrderBalance());
//        Boolean isTrue = Alipay.checkAliPayOrder(xmlMap,outTradeNo,totalAmount);
//        // 支付成功，商户处理后同步返回给微信参数
//        if (!isTrue) {
//            LOGGER.error("=========支付宝回调处理失败========="+result);
//            out.print("failure");
//        } else {
//            handleOrder(xmlMap,out);
//        }
//    }

//    @RequestMapping("test")
//    public void test() {
//        ztcOrderManager.updateCarOrderStatusByPay("123456",false);
//    }

//    /**
//     * 业务处理
//     * @param xmlMap 异步回调返回的数据
//     * @param out 输出流
//     */
//    private void handleOrder(Map<String, String> xmlMap,PrintWriter out){
//        if (ztcOrderManager.getOrderStatus(xmlMap.get("out_trade_no"))==1) {
//            //开始处理业务
//            if("ticket".equals(xmlMap.get("attach")) || "ticket".equals(xmlMap.get("passback_params"))){
//                //订票订单业务处理
//                ztcOrderManager.updateCarOrderStatusByPay(xmlMap.get("out_trade_no"),false);
//            }else if ("recharge".equals(xmlMap.get("attach")) || "recharge".equals(xmlMap.get("passback_params"))){
//                //充值订单业务处理
//                ztcOrderManager.updateRechargeOrderStatusByPay(xmlMap.get("out_trade_no"));
//            }else{
//                LOGGER.error("=========业务类型不匹配========="+xmlMap.toString());
//                return;
//            }
//            out.print("SUCCESS");
//        } else {
//            LOGGER.info("=========重复请求=========");
//            out.print("SUCCESS");
//        }
//    }
}